#!/usr/bin/env node

import { Command } from 'commander';
import { connect, start } from 'pm2';
const program = new Command();
import { build } from "./utils"
import { uploadDirToFtp } from './uploadFileToFtp';
import { join } from 'path';
import { stat } from 'fs-extra';
import { exec } from 'child_process';

const root = process.cwd()

program
    .version('1.0.0')
    .description('autojsprov2 命令行工具 微信：imeepos');

// 打包上传命令
program
    .command('build')
    .option('--ftp <url>', 'FTP 连接字符串')
    .action(async (options) => {
        const fileStat = await stat(join(root, 'src'))
        if (!fileStat.isDirectory()) {
            console.log(`src目录不存在`)
            return;
        }
        build(join(root, 'src'), false, async () => {
            if (options.ftp) {
                const ftp = new URL(options.ftp)
                await uploadDirToFtp(root, decodeURIComponent(ftp.pathname), {
                    host: ftp.hostname,
                    user: ftp.username,
                    password: ftp.password,
                    port: parseInt(ftp.port),
                })
                console.log('上传成功', options.ftp);
            }
        })
    });

// 监控命令
program
    .command('watch')
    .option('--ftp <url>', 'FTP 连接字符串（可选）')
    .action(async (options) => {
        const fileStat = await stat(join(root, 'src'))
        if (!fileStat.isDirectory()) {
            console.log(`src目录不存在`)
            return;
        }
        build(join(root, 'src'), true, async () => {
            if (options.ftp) {
                console.log(options.ftp)
                const ftp = new URL(options.ftp)
                await uploadDirToFtp(root, decodeURIComponent(ftp.pathname), {
                    host: ftp.hostname,
                    user: ftp.username,
                    password: ftp.password,
                    port: parseInt(ftp.port),
                })
                console.log('上传成功', options.ftp);
            }
        })
    });



program
    .command(`serve`)
    .action(async (options) => {
        exec(`pm2 start ${join(__dirname, 'main.js')} --name=autojsprov2`, (err, stdout, stderr) => {
            if (err) {
                console.error(err)
            } else {
                if (stdout) console.log(stdout)
                if (stderr) console.error(stderr)
            }
        })
    })
// 解析命令行输入
program.parse(process.argv);

// 如果没有提供有效命令，则显示帮助信息
if (!program.args.length) {
    program.help();
}